package tcp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class MyClient {

    public static void main(String[] args) {
        Socket client = null;
        boolean flag = true;

        //输入流：负责获得客户端发来的消息。
        BufferedReader input = null;
        //输入流：负责从控制台获得用户输入的字符串。
        BufferedReader in = null;
        //输出流：负责给客户端发消息。(因为给屏幕输出，所以应该使用PrintStream)
        PrintStream output = null;
        try {
            //首先连接服务器
            client = new Socket("localhost", 9999);
            input = new BufferedReader(new InputStreamReader(client.getInputStream()));
            in = new BufferedReader(new InputStreamReader(System.in));
            output = new PrintStream(client.getOutputStream());

            while (flag) {
                //首先给服务发送消息
                System.out.println("请输入内容：");
                String msg = in.readLine();
                if (msg == null || "".equals(msg) || "bye".equals(msg)) {
                    flag = false;
                    //最后这个'bye'必须发送给服务器
                    output.println(msg);
                } else {
                    output.println("客户端：" + msg);
                    //获得服务发来的消息
                    msg = input.readLine();
                    if (msg == null || "".equals(msg) || "bye".equals(msg)) {
                        flag = false;
                    } else {
                        System.out.println(msg);
                    }
                }
            }
            input.close();
            in.close();
            output.close();
            client.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
